<?php

// no direct access
defined( '_VALID_MOS' ) or die( 'Restricted access' );
global $mainframe;

require_once $mainframe->getPath('admin_html','com_logs'); 

$task      = mosGetParam($_REQUEST,'task');

switch ($task){
    case 'reports':
        reports();
        break;
    case 'purge':
        purge();
        break;
}

function reports(){
    global $database,$mosConfig_mailfrom, $mosConfig_fromname, $mosConfig_sitename;
    
    $formValues['company'] = mosGetParam($_REQUEST,'company',-1);
    $formValues['report'] = mosGetParam($_REQUEST,'report',1);
    $formValues['raw'] = mosGetParam($_REQUEST,'raw',0);
    $formValues['emailit'] = mosGetParam($_REQUEST,'emailit',0);
    $formValues['adminfields'] = mosGetParam($_REQUEST,'adminfields',0);
    $formValues['from'] = mosGetParam($_REQUEST,'from','');
    $formValues['to'] = mosGetParam($_REQUEST,'to','');
    $formValues['emailto'] = mosGetParam($_REQUEST,'emailto','author');
    $formValues['email'] = mosGetParam($_REQUEST,'email','');
    
    $query = "SELECT DISTINCT do.user_id, u.username, u.email FROM #__docman_owners AS do INNER JOIN #__users AS u ON do.user_id = u.id";
    $database->setQuery($query);
    $users = $database->loadObjectList();

    $emailReport = '';
    $companies[] = MOSHTML::makeoption('-1','All Advertisers');    
    foreach((array)$users as $key => $user){
        $companies[] = MOSHTML::makeoption($user->user_id,$user->username);
        if ($formValues['emailto'] == 'author' && $formValues['company'] == $user->user_id){
            $emailReport = $user->email;
        }
    }

    $lists['companies'] = MOSHTML::selectList($companies,'company','onchange="switchEmail();"','value','text',$formValues['company']);

    $reports[] = MOSHTML::makeoption('1','Company Summary');
    $reports[] = MOSHTML::makeoption('2','Company Activity');
    $reports[] = MOSHTML::makeoption('3','Detail Log');
    $lists['reports'] = MOSHTML::selectList($reports,'report','','value','text',$formValues['report']);

    $extraCBFields = getExtraFieldNames();
    
    $rows = doReports($formValues);
    if ( $formValues['raw'] ){
        downloadReport($rows, $formValues);
    }else if ($formValues['emailit']) {
         if ($formValues['emailto'] == 'specificemail' && $formValues['email'] != ''){
            $emailReport = $formValues['email'];
        }
        if ($emailReport){
            ob_start();
            logs_html::reports($rows, $formValues, $extraCBFields);
            $reporteHTML = ob_get_contents();
            ob_end_clean();
            $reporteHTML = '<html><head><title>Downloads Report at '.$mosConfig_sitename.' </title></head><body>'.$reporteHTML.'</body></html>';
            mosMail($mosConfig_mailfrom, $mosConfig_fromname, $emailReport, 'Downloads Report '.$mosConfig_sitename, $reporteHTML,true);
        }
        logs_html::filter($formValues, $lists);
        echo $reporteHTML;
    }else{
        logs_html::filter($formValues, $lists);
        logs_html::reports($rows, $formValues, $extraCBFields);
    }
}

function doReports($formValues){
    global $database;

    $rows = array();

    $companyWHERE = '';
    if ($formValues['company'] > 0){
        $companyWHERE = 'AND do.user_id = '.$formValues['company'];
    }

    $extrafields = '';
    $groupBy = "";
    if ($formValues['report'] == 1){
        $groupBy = ' GROUP BY ';
        if ($formValues['adminfields']) {
            $extrafields = ', el.ammount';
        }
        $extrafields .= ", count(*) as hits";
        $groupBy = ' GROUP BY u.name, d.dmname';
        if ($formValues['adminfields']) {
            $groupBy .= ', el.ammount';
        }
    }else {
        $extrafields = ', el.id, el.date, el.question1, el.answer1, el.question2, el.answer2, el.question3, el.answer3';
        if ($formValues['report'] == 3){
            $extrafields .= ', el.extra1, el.extra2, el.extra3, el.extra4, el.extra5, el.extra6, el.extra7, el.extra8, el.extra9';
        }
        if ($formValues['adminfields']) $extrafields .= ', el.ammount ';
    }

    if ($formValues['from'] && $formValues['to']){
        $query = "SELECT  u.name, u1.name as nameofuser, d.dmname {$extrafields} FROM (((( #__docman_extended_logs AS el LEFT JOIN #__docman AS d ON el.document_id = d.id)"
               . "\n LEFT JOIN #__users AS u1 ON el.user_id = u1.id)"
               . "\n LEFT JOIN  #__docman_owners AS do ON el.document_id = do.document_id ) LEFT JOIN #__users AS u ON do.user_id = u.id )   "
               . "\n WHERE date >= '{$formValues['from']} 00:00:00' AND date <= '{$formValues['to']} 23:59:59'"
               . "\n ".$companyWHERE
               . "\n ".$groupBy;

        $database->setQuery($query);
        $rows = $database->loadObjectList();
    }

    return $rows;
}

function downloadReport($rows, $formValues){
    @ob_end_clean();
    ob_start();

    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header('Content-type: application/vnd.ms-excel');
    header("Content-Transfer-Encoding: binary");
    header('Content-Disposition: attachment;filename=report.csv');

    foreach($rows as $key => $row){ 
        if ($formValues['report'] > 1){
            echo $row->id;
            echo ';'.$row->date.';';
        }
        echo $row->name;
        echo ';'.$row->dmname;
        if ($formValues['adminfields']){
            echo ';'.$row->ammount;
        }
            if ($formValues['report'] > 1 ){
            echo ';'.$row->nameofuser;
                echo ';'.$row->question1;
                echo ';'.$row->answer1;
                echo ';'.$row->question2;
                echo ';'.$row->answer2;
                echo ';'.$row->question3;
                echo ';'.$row->answer3;
        }
        if ($formValues['report'] == 1 ){
            echo ';'.$row->hits;
        }
        if ($formValues['report'] == 3 ){
            echo ';'.$row->extra1;
            echo ';'.$row->extra2;
            echo ';'.$row->extra3;
            echo ';'.$row->extra4;
            echo ';'.$row->extra5;
            echo ';'.$row->extra6;
            echo ';'.$row->extra7;
            echo ';'.$row->extra8;
            echo ';'.$row->extra9;
        }
        echo "\n";
    }
    ob_end_flush();
    exit();
}

function purge(){
    global $database;
    
    $formValues['from'] = mosGetParam($_REQUEST,'from','');
    $formValues['to'] = mosGetParam($_REQUEST,'to','');

    $formValues['adminfields'] = 1;
    $formValues['company'] = -1;
    $formValues['report'] = 3;
    $formValues['raw'] = 1;
    
    logs_html::filter_purge();
    if ($formValues['from'] && $formValues['to']){
        $rows = doReports($formValues);
        $query = "DELETE FROM  #__docman_extended_logs "
               . "\n WHERE date >= '{$formValues['from']} 00:00:00' AND date <= '{$formValues['to']} 23:59:59'";
        $database->setQuery($query);       
        $database->query();
        downloadReport($rows, $formValues);
    }

}

function getExtraFieldNames(){
    global $database, $_MAMBOTS, $mosConfig_absolute_path;

    require_once($mosConfig_absolute_path.'/components/com_comprofiler/plugin/language/default_language/default_language.php');
    if ( !isset($_MAMBOTS->_content_mambot_params['botlogs']) ) {

        $query = "SELECT params"
        . "\n FROM #__mambots"
        . "\n WHERE element = 'botlogs'"
        . "\n AND folder = 'docman'"
        ;
        $database->setQuery( $query );
        $database->loadObject($mambot);
        
        $_MAMBOTS->_content_mambot_params['botlogs'] = $mambot;
    }

    $mambot = $_MAMBOTS->_content_mambot_params['botlogs'];
    
    $botParams = new mosParameters( $mambot->params );

    $extra[1]['name'] = $botParams->get('extra1','');
    $extra[2]['name'] = $botParams->get('extra2','');
    $extra[3]['name'] = $botParams->get('extra3','');
    $extra[4]['name'] = $botParams->get('extra4','');
    $extra[5]['name'] = $botParams->get('extra5','');
    $extra[6]['name'] = $botParams->get('extra6','');
    $extra[7]['name'] = $botParams->get('extra7','');
    $extra[8]['name'] = $botParams->get('extra8','');
    $extra[9]['name'] = $botParams->get('extra9','');
    
    $query = "SELECT * FROM #__comprofiler_fields";
    $database->setQuery($query);
    $fields = $database->loadObjectList();

    foreach($fields as $key => $field){
        for($i=1;$i<=9;$i++){
            if ($field->name == $extra[$i]['name']){
                if(defined($field->title)){
                    $extra[$i]['title'] = constant($field->title);
                }else{
                    $extra[$i]['title'] = $field->title;
                }
            }
        }
    }
    return $extra;
}
?>
